import { request } from '../../utils/request.js'
let that
Page({

  /**
   * 页面的初始数据
   */
  data: {
    loginType:'password',
    countDown:false,
    captchaShow:'获取验证码',
    phone:'',
    password:'',
    captcha:'',
    isCheck:false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    that = this
  },
  inputhandle: e => {
    const key = e.target.dataset.key
    const inputValue = e.detail.value
    // console.log(e)
    that.setData({
      [key]:inputValue
    })
    // if(id === 'phoneNumber') that.setData({
    //   phoneNumber:inputValue
    // })
    // else if(id === 'password') that.setData({
    //   password:inputValue
    // })
  },
  checkPhone: (phone) => {
    const phoneReg = /^1[3-9]\d{9}$/;
    if(phone === '') return {
      title:'手机号不能为空',
      icon:'none'
    }
    else if(!phoneReg.test(phone)) return {
      title:'手机号码格式不合法',
      icon:'none'
    }
  },
  handleLogin: async () => {
    const { phone, password, captcha, loginType } = that.data
    function checkInfo(){
      const phoneResult = that.checkPhone(phone)
      if(phoneResult === undefined){
        if(loginType === 'password') return (
          password === ''?
          {
            title:'密码不能为空',
            icon:'none'
          }:{
            title:'验证通过'
          })
      else if(loginType === 'captcha') return (
          captcha === ''?
          {
            title:'验证码不能为空',
            icon:'none'
          }:{
            title:'验证通过'
          }
          )
      }
      else return phoneResult
      } 
    const checkResult = checkInfo()
    if(typeof (checkResult&&checkResult.icon) !== 'undefined') return wx.showToast(checkResult)
    else {
      const checkResultBackend = loginType === 'password'? await request('login/cellphone', {phone, password}) : await request('login/cellphone', {phone, captcha})
      if(checkResultBackend.code === 200) {
        //cookie也保存进本地数据, 这里的cookie是一大串字符串, 不好截取, 但是在request里面判断会影响request性能
        const cookie = that.getCookieFromData(checkResultBackend.cookie)
        try{
          wx.setStorageSync('cookie', cookie)
        }catch(e){
            console.log('cookie保存失败')
          }
        //加入本地存储, 在personal页面再读取本地存储
        try{wx.setStorageSync('userInfo', checkResultBackend.profile)}catch(e){
          console.log('用户信息保存失败')
        }
        return wx.reLaunch({
        url:'/pages/personal/personal'
      })
    }
      else return wx.showToast({
        title:"网络错误登录失败, 请再试一次",
        icon:'none'
      })
      //网易云音乐的账号密码登录可能会出现网络拥堵的情况, 暂时都使用验证码登录测试
      // const { code } = checkResultBackend
      // if(code !== 200){
      //   const checkMsg = code === 501?'账户不存在':'账户或者密码错误'
      //   return wx.showToast({
      //     title:checkMsg,
      //     icon:'none'
      //   })
      // }else {
      //   console.log(checkResultBackend)
      // }
    }
  },
  changeCaptcha: async() => {
    //修改登录方式为手机+验证码
    //将密码框的data-key修改为captcha
    that.setData({
      loginType:'captcha'
    })
  },
  //获取验证码
  getCaptcha: async() => {
    const { phone } = that.data
    const phoneResult = that.checkPhone(phone)
    if(phoneResult === undefined){
      const captchaResult = await request('captcha/sent', {phone})
      if(captchaResult.data === true) {
        wx.showToast({
          title:'验证码获取成功'
        })
        let seconds_to_go = 60
        //调用倒计时模块
        that.countDown(seconds_to_go)
      }
      else {
        wx.showToast({
          title:'验证码发送失败, 请稍后再试',
          icon:'none'
        })
      }
    }
    else return wx.showToast(phoneResult)
  },
  //倒计时
  countDown: (seconds_to_go) => {
    if(seconds_to_go <=0) return that.setData({
      captchaShow:'重新获取',
      countDown:false
    })
    else {
      // 渲染倒计时时钟
      that.setData({
        captchaShow: `${seconds_to_go}s`,
        countDown:true
      });
      seconds_to_go--;
      if (that.data.countDown == true) {
        setTimeout(() => that.countDown(seconds_to_go)
        ,1000)
      } else {
        that.setData({
          captchaShow: "获取验证码"
        });
      }
    }
  },
  getCookieFromData: (cookieData) => {
    const startIndex = cookieData.indexOf('MUSIC_U')
    const endIndex = cookieData.indexOf('MUSIC', startIndex+1)
/*  ----一种情况MUSIC_U后面没有MUSIC,
        那么endIndex = -1, 此时startIndex之后就是cookie
    ----另一种情况MUSIC_U后面有MUSIC,
        那么startIndex~endIndex-1(即slice(startIndex, endIndex))就是cookie, 不过这种情况下, MUSIC_U和后面的MUSICXX中间还有一个";"
        所以要去掉分号, slice(startIndex, endIndex-1) */
    if(endIndex === -1) {
      return cookieData.slice(startIndex)
    }
    else return cookieData.slice(startIndex, endIndex-1)
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})